/*
 * Will create a prediction file adding the 2 given prediction files.
 * The assumption is that neither file is complete without the other.
 * This is commonly used for adding residual prediction files to their corresponding effects prediction files.
 * If the first prediction file is unfinished then the result file will contain entries for predictions from the first file
 * If the second prediction file is unfinished then the remaining entries in the result file will be the values from the first file
 */
#include <stdio.h> 
#include <stdlib.h>
#include <string.h>

using namespace std;

int main(int argc, char **argv){
  if( argc != 4 ){
    fprintf(stderr, "Need to supply 2 prediction files and an output file.\n");
    exit(EXIT_FAILURE);
  }
  char predLine1[256], predLine2[256];
  //Open prediction files and output file
  FILE *predFile1 = fopen(argv[1], "r");
  FILE *predFile2 = fopen(argv[2], "r");
  FILE *outFile = fopen(argv[3], "w");
  double prediction1, prediction2, prediction;
  //Read line by line from both files simultaneously
  while(fgets(predLine1, 256, predFile1)){
    fgets(predLine2, 256, predFile2);
    if(predLine1[strlen(predLine1)-2] == ':')//New Movie
      fputs(predLine1, outFile);
    else{ //It is a prediction line
      prediction1 = atof(predLine1);
      prediction2 = atof(predLine2);
      prediction = prediction1 + prediction2;
      //Make sure predictions are between 1 and 5
      if(prediction > 5) prediction = 5;
      if(prediction < 1) prediction = 1;
      fprintf(outFile, "%lf\n", prediction);//Write prediction
    }
    if(feof(predFile2))//Second file unfinished
      break;
  }
  //This while loop only gets executed if the second file is shorter than the first.
  while(fgets(predLine1, 256, predFile1)){//use only first file if second isn't finished past this point
    if(predLine1[strlen(predLine1)-2] == ':')//New Movie
      fputs(predLine1, outFile);
    else{ //CustomerID, date
      prediction1 = atof(predLine1);
      if(prediction1 > 5) prediction1 = 5;
      if(prediction1 < 1) prediction1 = 1;
      fprintf(outFile, "%lf\n", prediction1);
    }
  }
  fclose(predFile1);
  fclose(predFile2);
  fclose(outFile);
}
